package com.wxc.util;

import java.io.*;

/**
 * @author wxc
 * @date 2021年10月06日 14:29
 */
public class StreamUtil {
    public static byte[] streamToByteArray(InputStream inputStream) {
        ByteArrayOutputStream byteArrayOutputStream = null;
        byte[] bytes = null;
        try {
            byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int readlen;
            while ((readlen = inputStream.read(b)) != -1) {
                byteArrayOutputStream.write(b, 0, readlen);
            }
            bytes = byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (byteArrayOutputStream != null) {
                    byteArrayOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bytes;
    }

    public static String streamToString(InputStream inputStream) {
        BufferedReader bufferedReader = null;
        StringBuilder stringBuilder = new StringBuilder();
        try {
            bufferedReader = new BufferedReader(
                    new InputStreamReader(inputStream));
            char[] chars = new char[1024];
            int readlen;
            while((readlen = bufferedReader.read(chars)) != -1) {
                stringBuilder.append(new String(chars,0,readlen));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return stringBuilder.toString();
    }

    public static void writeToFile(String fileName,byte[] bytes) {
        BufferedOutputStream bufferedOutputStream = null;
        try {
            bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(fileName));
            bufferedOutputStream.write(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(bufferedOutputStream != null) {
                try {
                    bufferedOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
